import WxValidate from '../../../utils/WxValidate.js';
import http from '../../../utils/http.js';
import ocr from '../../../utils/ocr.js';

import businessDict from '../../../utils/dict.js';

const {
  $Message
} = require('../../../component/iview/base/index');


//车辆信息
// const vehicleField = [{
//     "text": "车架号",
//     "field": "vehicle.vin",
//     rule: {
//       "required": true,
//       "maxlength": 32,
//       "enNum": true,
//     },
//     message: {
//       "required": "车架号不能为空",
//       "maxlength": "车架号不能超过32个字符",
//       "enNum": '车架号只能输入英文和数字'
//     }
//   }, {
//     "text": "车辆品牌",
//     "field": "vehicle.brand",
//     rule: {
//       "required": true,
//       "maxlength": 64,
//     },
//     message: {
//       "required": "车辆品牌不能为空",
//       "maxlength": "车辆品牌不能超过64个字符",
//     }
//   }, {
//     "text": "车辆型号",
//     "field": "vehicle.carmodel",
//     rule: {
//       "required": true,
//       "maxlength": 64,
//     },
//     message: {
//       "required": "车辆型号不能为空",
//       "maxlength": "车辆型号不能超过64个字符",
//     }
//   }, {
//     "text": "车辆类型",
//     "field": "vehicle.vehicleType",
//     select: true,
//     rule: {
//       "required": true,
//     }
//   }, {
//     "text": "发动机型号",
//     "field": "vehicle.engineModel",
//     rule: {
//       "required": true,
//       "maxlength": 64,
//       "lineEnNum": true
//     },
//     message: {
//       "required": "发动机型号不能为空",
//       "maxlength": "发动机型号不能超过64个字符",
//       "lineEnNum": "发动机型号只能是英文和数字和横杠"
//     }
//   }, {
//     "text": "发动机号",
//     "field": "vehicle.engineNo",
//     rule: {
//       "required": true,
//       "maxlength": 64,
//       "lineEnNum": true
//     },
//     message: {
//       "required": "发动机号不能为空",
//       "maxlength": "发动机号不能超过64个字符",
//       "lineEnNum": "发动机号只能是英文和数字和横杠"
//     }
//   }, {

//     "text": "出厂日期",
//     "field": "vehicle.productionDate",
//     rule: {
//       "required": true,
//     },
//     message: {
//       "required": "出厂日期不能为空",

//     }
//   },
//   //   {

//   //   "text": "出厂日期",
//   //   "field": "vehicle.productionDate",
//   //   date: true,
//   //   rule: {
//   //     "required": true,
//   //   }
//   // }, 
//   {
//     "text": "燃油种类",
//     "field": "vehicle.fuelType",
//     select: true,
//     rule: {
//       "required": true,
//     }
//   }, {
//     "text": "使用性质",
//     "field": "vehicle.useProperty",
//     select: true,
//     rule: {
//       "required": true,
//     }
//   }, {
//     "text": "是否进口车",
//     "field": "vehicle.isImported",
//     select: true,
//     rule: {
//       "required": true,
//     }
//   }, {
//     "text": "排放标准",
//     "field": "vehicle.emissionStandard",
//     select: true,
//     rule: {
//       "required": true,
//     }
//   }, {
//     "text": "号牌种类",
//     "field": "vehicle.plateType",
//     select: true,
//     rule: {
//       "required": true,
//     }
//   }


// ];
const vehicleField = [{
    "text": "车架号",
    "field": "vin",
    rule: {
      "required": true,
      "maxlength": 32,
      "enNum": true,
    },
    message: {
      "required": "车架号不能为空",
      "maxlength": "车架号不能超过32个字符",
      "enNum": '车架号只能输入英文和数字'
    }
  }, {
    "text": "车辆品牌",
    "field": "brand",
    rule: {
      "required": true,
      "maxlength": 64,
    },
    message: {
      "required": "车辆品牌不能为空",
      "maxlength": "车辆品牌不能超过64个字符",
    }
  }, {
    "text": "车辆型号",
    "field": "model",
    rule: {
      "required": true,
      "maxlength": 64,
    },
    message: {
      "required": "车辆型号不能为空",
      "maxlength": "车辆型号不能超过64个字符",
    }
  },
  {
    "text": "发动机型号",
    "field": "engineModel",
    rule: {
      "required": true,
      "maxlength": 64,
      "lineEnNum": true
    },
    message: {
      "required": "发动机型号不能为空",
      "maxlength": "发动机型号不能超过64个字符",
      "lineEnNum": "发动机型号只能是英文和数字和横杠"
    }
  },
  {
    "text": "发动机号",
    "field": "engineNo",
    rule: {
      "required": true,
      "maxlength": 64,
      "lineEnNum": true
    },
    message: {
      "required": "发动机号不能为空",
      "maxlength": "发动机号不能超过64个字符",
      "lineEnNum": "发动机号只能是英文和数字和横杠"
    }
  },
  {
    "text": "座位数量",
    "field": "limitPassenger",
    rule: {
      "required": true,
      "digits": true,
    },
    message: {
      "required": "座位数量不能为空",
      "maxlength": "座位数量不能超过64个字符",
      "lineEnNum": "座位数量只能是英文和数字和横杠"
    }
  },

  {

    "text": "出厂日期",
    "field": "productionDate",
    date: true,
    select: true,
    rule: {
      "required": true,
    },
    message: {
      "required": "出厂日期不能为空",

    }
  },
  {
    "text": "燃油种类",
    "field": "fuelType",
    select: true,
    rule: {
      "required": true,
    }
  },
  {
    "text": "车辆类型",
    "field": "vehicleType",
    select: true,
    rule: {
      "required": true,
    }
  },
  {
    "text": "使用性质",
    "field": "useProperty",
    select: true,
    rule: {
      "required": true,
    }
  },
  {
    "text": "排放标准",
    "field": "emissionStandard",
    select: true,
    rule: {
      "required": true,
    }
  }, {
    "text": "号牌种类",
    "field": "plateType",
    select: true,
    rule: {
      "required": true,
    }
  }


];
//车主信息
const owner = [{
    "text": "证件编号",
  "field": "creditNo",
    rule: {
      "required": true,
      "creditNo": true
    },
    message: {
      "required": "证件编号不能为空",
      "creditNo": "请输入正确的证件编号"
    }
  }, {
    "text": "买方名称",
    "field": "name",
    rule: {
      "required": true,
      "maxlength": 32
    },
    message: {
      "required": "买方名称不能为空",
      "maxlength": "买方名称不能超过32个字符"
    }
  }, {
    "text": "居住地址",
    "field": "address",
    "textarea": true,
    rule: {
      "required": true,
      "maxlength": 128
    },
    message: {
      "required": "居住地址不能为空",
      "maxlength": "居住地址不能超过128个字符"
    }
  },
  {
    "text": "联系电话",
    "field": "tel",
    rule: {
      "required": true,
      "tel": true
    },
    message: {
      "required": "联系电话不能为空",
      "tel": "电话号码不正确"
    }

  },
];





Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeheight: 0,
    commission: null, //本次交易的费用
    show: false, //是否弹窗
    currentStep: 0,
    formField: [
      owner, vehicleField
    ],
    // formField: {
    //   vehicle: vehicleField,
    //   buyer: person,
    //   seller: person
    // },
    files: {},
    filesFlag: {},
    filesField: [{
        text: '身份证明',
        flag: 0,
        field: 'identificationImg',

        hidden: true,
      }, {
        text: '车辆合格证/货物进出口证明',
        flag: 0,
        field: 'certificateImg',
        hidden: true,
      }, {
        text: '环保清单',
        flag: 0,
        field: 'envCheckListImg',
        "required": true,
      },
      {
        text: '一致性证书',
        flag: 1,
        field: 'conformityCertImg'
      }

    ],
    formDict: {
      "isImported": [{
        code: '0',
        name: '非进口车'
      }, {
        code: '1',
        name: '进口车'
      }]
    },
    // formData: {
    //   "vehicle.isImported": '0',
    //   // "destination": '福建省厦门市',
    //   "owner.creditType": "P1",
    //   "vehicle.vehicleType": "K33",
    //   "vehicle.fuelType": "A",
    //   "vehicle.useProperty": "A",
    //   "vehicle.emissionStandard": "绿标",
    //   "vehicle.plateType": "A"
    //   // "buyer.creditType": "P1",
    // },
    formData: {
      "isImported": '0',
      // "destination": '福建省厦门市',
      "creditType": "P1",
      // "vehicleType": "K33",
      // "fuelType": "A",
      // "useProperty": "A",
      // "emissionStandard": "绿标",
      // "plateType": "A"
      // "buyer.creditType": "P1",
    },
    // formSelectData: {
    //   "vehicle.isImported": 0,
    //   "vehicle.vehicleType": 0,
    //   "vehicle.fuelType": 0,
    //   "vehicle.useProperty": 0,
    //   "vehicle.emissionStandard": 0,
    //   "vehicle.plateType": 0
    // },
    formSelectData: {
      "isImported": 0,
      "vehicleType": 0,
      "fuelType": 0,
      "useProperty": 0,
      "emissionStandard": 0,
      "plateType": 0
    },


    ocrFile: [{
      step: 0,
      field: 'identificationImg',
      text: '请上传车主证件正面照片，将自动识别信息',
      bgClass: 'id-card-image',
      // creditTypeField: "owner.creditType",
      creditTypeField: "creditType",
      bgClass: {
        "P1": 'id-card-image',
        "C3": 'business-license-image',
      }
    }, {
      step: 1,
      field: 'certificateImg',
      text: '请上传车辆合格证，将自动识别信息',
      // creditTypeField: "vehicle.isImported",
      creditTypeField: "isImported",
      bgClass: {
        "0": 'certificateImg',
        "1": 'certificateImg',
      }
    }],
    // ocrFile: [{
    //   step: 1,
    //   field: 'vehicleLicense',
    //   text: '请上传行驶证主页照片，将自动识别信息',
    //   bgClass: 'vehicle-license-image'
    // }, {
    //   step: 2,
    //   field: 'buyerCreditFront',
    //   text: '请上传买家证件正面照片，将自动识别信息',
    //   bgClass: 'id-card-image',
    //   creditTypeField: "buyer.creditType",
    //   bgClass: {
    //     "P1": 'id-card-image',
    //     "C3": 'business-license-image',
    //   }
    // }, {
    //   step: 3,
    //   field: 'sellerCreditFront',
    //   text: '请上传卖家证件正面照片，将自动识别信息',
    //   creditTypeField: "seller.creditType",
    //   bgClass: {
    //     "P1": 'id-card-image',
    //     "C3": 'business-license-image',
    //   }
    // }],

    confirmShow: false, //用来展示是否切换个人和企业
    confirmField: '', //确定要更改的字段
    confirmValue: '', //确定要更改后的值
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // console.log(formData)
    // let dictFieldArray = ["vehicle.vehicleType", "vehicle.fuelType",
    //   "vehicle.useProperty", "vehicle.emissionStandard",
    //   "vehicle.plateType",
    //   //"buyer.creditType", "seller.creditType",
    //   // "transferType",
    //   // "tradeVehicleType"
    // ];
    let dictFieldArray = ["vehicleType", "fuelType",
      "useProperty", "emissionStandard",
      "plateType",
      //"buyer.creditType", "seller.creditType",
      // "transferType",
      // "tradeVehicleType"
    ];
    let dictCategoryArray = ["VEHICLE_TYPE", "VEHICLE_FUEL_TYPE",
      "VEHICLE_USE_PROPERTY", "VEHICLE_EMISSION_STANDARD",
      "VEHICLE_PLATE_TYPE",
      //"CREDIT_TYPE", "CREDIT_TYPE",
      // "Transfer_Type",
      // "TRADE_VEHICLE_TYPE"
    ];

    for (let i = 0; i < dictFieldArray.length; i++) {
      //加载相关字典
      this.loadDict(dictCategoryArray[i], dictFieldArray[i]);
    }
    // this.loadDict("VEHICLE_TYPE", "vehicle.vehicleType");
    // this.loadDict("VEHICLE_FUEL_TYPE", "vehicle.fuelType");
    // this.loadDict("VEHICLE_USE_PROPERTY", "vehicle.useProperty");
    // this.loadDict("VEHICLE_EMISSION_STANDARD", "vehicle.emissionStandard");
    // this.loadDict("VEHICLE_PLATE_TYPE", "vehicle.plateType");
    // this.loadDict("CREDIT_TYPE", "buyer.creditType");
    // this.loadDict("CREDIT_TYPE", "seller.creditType");
    this.initValidate();

    if (options.applicationId != null) {


      //加载要修改的数据
      http.request({
        url: '/wxNewcarinfo/detailForUpdate',
        method: "GET",
        data: {
          applicationId: options.applicationId
        },
        success: (res) => {
          // this.transferData(res, "buyer");
          // this.transferData(res, "seller");
          // this.transferData(res, "vehicle");
          // // this.transferData(res, "image");
          // //delete res["image"];
          // this.transferData(res, "ticket");

          let filesFlag = {};
          let image = {};
          // console.log(res)
          //身份证明
          // if(res[""])
          if (res["imageUrl"] != null) {
            let array = this.data.filesField;
            for (let i = 0; i < array.length; i++) {
              let field = array[i].field;
              // if (field =='vihecleInfo'){
              //   if (res['isImport'] == 0){
              //     let src = http.apiUrl + http.imgUrl + "?imagePath=" + res["imageUrl"]['certificateImg'] +
              //       "&" + wx.getStorageSync("sessionid")
              //     image[field] = encodeURI(src);
              //     filesFlag[field] = 0; // 0表示这是之前上传过的，1表示是新上传的
              //   }else{
              //     let src = http.apiUrl + http.imgUrl + "?imagePath=" + res["imageUrl"]['importCertImg'] +
              //       "&" + wx.getStorageSync("sessionid")
              //     image[field] = encodeURI(src);
              //     filesFlag[field] = 0; // 0表示这是之前上传过的，1表示是新上传的
              //   }

              // }else{
              if (res["imageUrl"][field] != null && res["imageUrl"][field] != '') {
                let src = http.apiUrl + http.imgUrl + "?imagePath=" + res["imageUrl"][field] +
                  "&" + wx.getStorageSync("sessionid")
                image[field] = encodeURI(src);
                filesFlag[field] = 0; // 0表示这是之前上传过的，1表示是新上传的
              }
              // }



            }
            // delete res["imageUrl"]
          }

          let formSelectData = this.data.formSelectData;
          for (let i = 0; i < dictFieldArray.length; i++) {
            this.dictToIndex(dictFieldArray[i], res[dictFieldArray[i]], formSelectData);
          }
          // this.dictToIndex("vehicle.vehicleType", res["vehicle.vehicleType"], formSelectData);
          // this.dictToIndex("vehicle.fuelType", res["vehicle.fuelType"], formSelectData);
          // this.dictToIndex("vehicle.useProperty", res["vehicle.useProperty"], formSelectData);
          // this.dictToIndex("vehicle.emissionStandard", res["vehicle.emissionStandard"], formSelectData);
          // this.dictToIndex("vehicle.plateType", res["vehicle.plateType"], formSelectData);
          // this.dictToIndex("buyer.creditType", res["buyer.creditType"], formSelectData);
          // this.dictToIndex("seller.creditType", res["seller.creditType"], formSelectData);
          formSelectData["isImported"] = res["isImport"];

          this.setData({
            formData: res,
            formSelectData: formSelectData,
            files: image,
            filesFlag: filesFlag
          });
        }
      });
      // } else {
      //   let formData = {};
      //   let formSelectData = {};
      //   for (let i = 0; i < dictFieldArray.length; i++) {
      //     var dict = this.data.formDict[dictFieldArray[i]];
      //     console.info(this.data.formDict);
      //     console.info(this.data.formDict[dictFieldArray[i]]);
      //     console.info(dictFieldArray[i]);
      //     if (dict != null && dict.length > 0) {
      //       let code = this.data.formDict[dictFieldArray[i]].code;
      //       formData[dictFieldArray[i]] = code;
      //       formSelectData[dictFieldArray[i]] = 0;
      //     }
      //   }
      //   this.setData({
      //     formData: formData,
      //     formSelectData: formSelectData
      //   });
      //   console.info(this.data)
    }
  },
  transferData: function(res, field) {
    let buyer = res[field];
    for (let key in buyer) {
      res[field + "." + key] = buyer[key];
    }
    delete res[field];
  },
  dictToIndex: function(field, value, formSelectData) {
    if (value == null || value == "") {
      formSelectData[field] = 0;
      return formSelectData;
    }
    var dict = this.data.formDict[field];
    if (dict != null && dict.length > 0) {
      for (var i = 0; i < dict.length; i++) {
        if (dict[i].code == value) {
          formSelectData[field] = i;
          break;
        }
      }
    }
    return formSelectData;
  },
  //加载字典信息
  loadDict: function(category, field) {
    let dictList = businessDict[category];
    if (dictList == null || dictList.length == 0) {
      wx.showLoading({
        title: '数据准备中...',
        mask: true
      })
      http.request({
        url: "/dict/findDict",
        data: {
          category: category
        },
        success: res => {
          businessDict[category] = res;
          this.handleDict(res, field);
          wx.hideLoading()
        }
      });
    } else {
      this.handleDict(dictList, field);
    }
  },
  handleDict: function(dictList, field) {
    let formDict = this.data.formDict;
    let formData = this.data.formData;
    let formSelectData = this.data.formSelectData;
    formDict[field] = dictList;
    formData[field] = dictList[0].code;
    formSelectData[field] = 0;
    this.setData({
      formDict: formDict,
      formData: formData,
      formSelectData: formSelectData
    });
  },
  bindDateChange: function(e) {
    console.log(e)
    let formData = this.data.formData;
    formData[e.currentTarget.dataset.field] = e.detail.value;
    this.setData({
      formData: formData
    });
  },
  bindDictChange: function(e) {
    let formData = this.data.formData;
    let formSelectData = this.data.formSelectData;
    let field = e.currentTarget.dataset.field;
    let index = e.detail.value;
    formSelectData[field] = index;
    formData[field] = this.data.formDict[field][index]["code"];
    if (field === "transferType" && formData[field] == 2) {
      let dict = this.data.formDict["tradeVehicleType"];
      let index = formSelectData["tradeVehicleType"];
      for (let i = 0; i < dict.length; i++) {
        if (dict[i]["code"] == "TRADE_TURN_OUT") {
          index = i;
        }
      }
      formSelectData["tradeVehicleType"] = index;
      formData["tradeVehicleType"] = "TRADE_TURN_OUT";
    }
    this.setData({
      formData: formData,
      formSelectData: formSelectData
    });
  },
  bindVal: function(e) {
    let formData = this.data.formData;
    let formSelectData = this.data.formSelectData;
    let field = e.currentTarget.dataset.field;
    let value = e.detail.value;
    // if (field === "vinNo") {
    //   if (value != null && value.length > 0) {
    //     if (value.substr(0, 1) == 'L') {
    //       formData["isImport"] = 0;
    //       formSelectData["isImport"] = 0;
    //     } else {
    //       formData["isImport"] = 1;
    //       formSelectData["isImport"] = 1;
    //     }
    //   }
    // }
    formData[field] = value;
    this.setData({
      formData: formData,
      formSelectData: formSelectData
    });
  },
  bindRegionChange: function(e) {
    let value = e.detail.value;
    let field = e.currentTarget.dataset.field;
    let formData = this.data.formData;
    formData[field] = value[0] + value[1];
    this.setData({
      formData: formData,
    });
  },
  //验证函数
  initValidate() {
    let fields = this.data.formField;
    let validate = [];
    for (let j = 0; j < fields.length; j++) {
      const rule = {};
      const message = {};
      let formField = fields[j];
      for (let i = 0; i < formField.length; i++) {
        rule[formField[i]["field"]] = formField[i]["rule"];
        message[formField[i]["field"]] = formField[i]["message"];
      }
      let wxValidate = new WxValidate(rule, message);
      validate.push(wxValidate);
    }
    this.WxValidate = validate;
  },
  //调用验证函数
  formSubmit: function(e) {
    const params = e.detail.value;
    console.log(params)
    //校验表单
    if (!this.WxValidate[this.data.currentStep].checkForm(params)) {
      const error = this.WxValidate[this.data.currentStep].errorList[0];
      $Message({
        content: error.msg,
        type: 'error'
      });
      return false
    }
    this.setData({
      currentStep: this.data.currentStep + 1
    });
  },
  //提交保存数据
  sumbitData: function() {
    let data = this.data.formData;
    let filesField = this.data.filesField;
    let files = this.data.files;
    for (let i = 0; i < filesField.length; i++) {
      if (filesField[i]["required"] === true) {
        if (files[filesField[i]["field"]] == null || files[filesField[i]["field"]] == "") {
          $Message({
            content: filesField[i]["text"] + "必须上传",
            type: 'error'
          });
          return;
        }
      }
    }


    // let that = this;
    // let tradeVehicleTypeDict = that.data.formDict["tradeVehicleType"];
    // let tradeVehicleType = that.data.formData["tradeVehicleType"];
    // let commission = 0;
    // for (let i = 0; i < tradeVehicleTypeDict.length; i++) {
    //   if (tradeVehicleTypeDict[i].code == that.data.formData["tradeVehicleType"]) {
    //     commission = tradeVehicleTypeDict[i].des;
    //     break;
    //   }
    // }
    // that.setData({
    //   commission: commission
    // })

    // wx.showLoading({
    //   title: '正在提交',
    //   mask: true
    // });
    // this.imageToBase64(0, {});
    // wx.showModal({
    //   title: '提交确认',
    //   content: '确认提交' + data['vinNo']+'车辆的挂牌申请',
    //   cancelText: '取消',
    //   confirmText: '确认',
    //   success(res) {
    //     if (res.cancel) {

    //     } else if (res.confirm) {
    //       wx.showLoading({
    //         title: '数据提交中',
    //         mask: true
    //       });
    //       this.imageToBase64(0, {})
    //     }
    //   }
    // })
    this.setData({
      show: true
    })
  },

  //
  setdes: function(value) {
    let formdata = this.data.formData;
    formdata['destination'] = value;

    this.setData({
      formData: formdata
    })
  },



  //
  imageToBase64: function(index, images) {
    let field = this.data.filesField[index]["field"];
    index++;
    if (this.data.filesFlag[field] == 1) {
      //说明这张图片是新增
      let file = this.data.files[field];
      wx.getFileSystemManager().readFile({
        filePath: file, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          images[field] = "data:image/jpeg;base64," + res.data;
          // console.info(res.data);
        },
        complete: () => {
          if (index < this.data.filesField.length) {
            this.imageToBase64(index, images);
          } else {
            this.saveData(images);
          }
        }
      })
    } else if (this.data.filesFlag[field] == 0) {
      //说明这张图片是修改时回显的
      images[field] = this.data.formData["imageUrl"][field] //直接上传原先的地址
      if (index < this.data.filesField.length) {
        this.imageToBase64(index, images);
      } else {
        this.saveData(images);
      }
    } else {
      if (index < this.data.filesField.length) {
        this.imageToBase64(index, images);
      } else {
        this.saveData(images);
      }
    }
  },
  //弹窗确认
  handleOK: function() {

    this.setData({
      show: false,
    })
    wx.showLoading({
      title: '数据提交中',
      mask: true
    });
    this.imageToBase64(0, {})
  },
  //弹窗取消
  handleCancel: function() {
    this.setData({
      show: false
    })
  },

  saveData: function(images) {
    var that = this;
    let formData = that.data.formData;
    // console.log(typeof (formData))
    // console.log(typeof (data))

    let isImport = formData['isImported']
    let data = JSON.parse(JSON.stringify(formData));
    for (let key in data) {
      if (data[key] == null) {
        delete data[key];
      }
    }
    delete data["image"];
    delete data["imageUrl"];
    if (images != null) {
      for (let key in images) {
        // if (isImport =="0" && key =="vihecleInfo"){
        //   data["image.certificateImg" ] = images[key];
        // } else if (isImport == "1" && key == "vihecleInfo"){
        //   data["image.importCertImg"] = images[key];

        // }else{
        data["image." + key] = images[key];
        // }
      }
    }
    // console.log('数据提交')
    // console.log(data);
    // console.log(typeof (data))

    http.request({
      url: '/wxNewcarinfo/save',
      method: "POST",
      data: data,
      success: (res) => {
        let pages = getCurrentPages();
        let prepage = pages[pages.length - 2];
        wx.hideLoading({});

        wx.navigateBack({
          delta: 1,
          complete: function() {
            //保存成功后，页面重新加载数据
            prepage.reloadData();

          }
        });
      },
      error: (res) => {
        wx.hideLoading({});
        $Message({
          content: "提交失败," + res.replace('ServiceException:', ''),
          type: 'error'
        });
      }
    });
  },
  //上一步
  previous: function(e) {
    this.setData({
      currentStep: this.data.currentStep - 1
    });
  },
  //
  handleCancel: function(e) {
    this.setData({
      show: false
    })
  },

  chooseWxImage: function(e) {
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#000",
      success: function(res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.doOcr(e, 'album')
          } else if (res.tapIndex == 1) {
            that.doOcr(e, 'camera')
          }
        }
      }
    })

  },

  //ocr图片识别
  doOcr: function(e, type) {
    var that = this;
    var imageType = 'VL';
    let iocrType = null;
    let currentStep = this.data.currentStep;
    var isImport = this.data.formData['isImported']

    if (currentStep == 0) {
      imageType = this.data.formData["creditType"];
      // imageType = this.data.formData["owner.creditType"];
    } else if (currentStep == 1) {
      if (isImport == 1) {
        imageType = 'iocr';

        iocrType = 'importeCert'
      } else {
        imageType = 'VC';
      }

    } else if (currentStep == 3) {
      imageType = this.data.formData["seller.creditType"];
    }
    wx.chooseImage({
      sizeType: ['compressed'],
      count: 1,
      sourceType: [type],
      success: function(res) {

        ocr.baiduOcr({
          imageType: imageType,
          filePath: res.tempFilePaths[0],
          iocrType: iocrType,
          success: function(resp) {

            var formData = that.data.formData;
            // console.log(formData)
            var formSelectData = that.data.formSelectData;
            if (that.data.currentStep == 0) {
              //识别车主信息
              if (imageType == "P1") {
                formData["creditNo"] = resp["公民身份号码"]["words"];
                formData["name"] = resp["姓名"]["words"];
                formData["address"] = resp["住址"]["words"];
                // formData["owner.creditNo"] = resp["公民身份号码"]["words"];
                // formData["owner.name"] = resp["姓名"]["words"];
                // formData["owner.residenceAddress"] = resp["住址"]["words"];
              } else if (imageType == 'C3') {
                formData["creditNo"] = resp["社会信用代码"]["words"];
                formData["name"] = resp["单位名称"]["words"];
                formData["address"] = resp["地址"]["words"];
                // formData["owner.creditNo"] = resp["社会信用代码"]["words"];
                // formData["owner.name"] = resp["单位名称"]["words"];
                // formData["owner.residenceAddress"] = resp["地址"]["words"];
              }
            } else if (that.data.currentStep == 1) {
              if (isImport == 1) {
                //处理进口车识别结果处理
                //车架号
                formData["vin"] = resp["ret"][1].word;
   
                // //发动机型号 与 发动机号
                // formData["engineModel"] = resp["EngineType"];
                formData["engineNo"] = resp["ret"][10].word;
                //出厂日期
                let productionDate = resp["ret"][8].word + "01"
                formData["productionDate"] = productionDate.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3");
                console.log('牛逼进口车')
                let info = resp["ret"][5].word;
                let len = info.length;
                let idx = info.indexOf('座');
                let idx1 = info.indexOf('CC');

                //座位数
                formData["limitPassenger"] = info.substring(idx - 1, idx);
                //车辆品牌
                formData["brand"] = info.substring(idx+1, idx1);
                // //车辆型号
                formData["model"] = info.substring(idx1+2, len);


              } else {
                //非进口车证明识别结果处理
                //车架号
                formData["vin"] = resp["VinNo"];
                //车辆品牌
                formData["brand"] = resp["CarBrand"];
                //车辆型号
                formData["model"] = resp["CarModel"];
                //发动机型号 与 发动机号
                formData["engineModel"] = resp["EngineType"];
                formData["engineNo"] = resp["EngineNo"];
                //出厂日期
                let manufactureDate = resp["ManufactureDate"];
                if (manufactureDate.indexOf("年") != -1) {
                  manufactureDate = manufactureDate.replace('年', '-')
                }
                if (manufactureDate.indexOf("月") != -1) {
                  manufactureDate = manufactureDate.replace('月', '-')
                }
                if (manufactureDate.indexOf("日") != -1) {
                  manufactureDate = manufactureDate.replace('日', '')
                }
                formData["productionDate"] = manufactureDate;

                //燃油种类识别
                var fuelTypeDict = that.data.formDict["fuelType"];
                if (fuelTypeDict != null && fuelTypeDict.length > 0) {
                  var fuelType = resp["FuelType"]
                  for (var i = 0; i < fuelTypeDict.length; i++) {
                    if (fuelTypeDict[i].name == fuelType) {
                      // formData["vehicle.fuelType"] = fuelTypeDict[i].code;
                      // formSelectData["vehicle.fuelType"] = i; 
                      formData["fuelType"] = fuelTypeDict[i].code;
                      formSelectData["fuelType"] = i;

                      break;
                    }
                  }
                }
                //排放标准
                var emissionStandardDict = that.data.formDict["emissionStandard"];
                if (emissionStandardDict != null && emissionStandardDict.length > 0) {
                  var emissionStandard = resp["EmissionStandard"]
                  for (var i = 0; i < emissionStandardDict.length; i++) {
                    console.log(emissionStandard);
                    console.log(emissionStandardDict[i].name)
                    if (emissionStandard.includes(emissionStandardDict[i].name)) {
                      // formData["vehicle.emissionStandard"] = emissionStandardDict[i].code;
                      // formSelectData["vehicle.emissionStandard"] = i;
                      formData["emissionStandard"] = emissionStandardDict[i].code;
                      formSelectData["emissionStandard"] = i;
                      break;
                    }
                  }
                }
              }

            }

            that.setData({
              formData: formData,
              formSelectData: formSelectData
            });

          },
        });

        let fileField = that.data.currentStep == 0 ? "identificationImg" : "certificateImg";
        let files = that.data.files;
        files[fileField] = res.tempFilePaths[0];
        var filesFlag = that.data.filesFlag;
        filesFlag[fileField] = 1; // 0表示这是之前上传过的，1表示是新上传的
        that.setData({
          files: files,
          filesFlag: filesFlag
        });

        // console.log(that.data.formData)
        // console.log(that.data.files)
      }
    });
  },
  //上传图片
  chooseImage: function(e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['compressed'],
      //sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      //sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      count: 1,
      success: function(res) {
        var files = that.data.files;
        files[e.currentTarget.dataset.field] = res.tempFilePaths[0];
        var filesFlag = that.data.filesFlag;
        filesFlag[e.currentTarget.dataset.field] = 1; // 0表示这是之前上传过的，1表示是新上传的
        that.setData({
          files: files,
          filesFlag: filesFlag
        });
      }
    })
  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.img, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.img] // 需要预览的图片http链接列表
    })
  },
  deleteImage: function(e) {
    var files = this.data.files;
    files[e.currentTarget.dataset.field] = null;
    var filesFlag = this.data.filesFlag;
    filesFlag[e.currentTarget.dataset.field] = null; // 0表示这是之前上传过的，1表示是新上传的
    this.setData({
      files: files
    });
  },

  //企业和个人orc识别按钮切换
  tabChange: function(e) {
    //显示确认框
    let field = e.currentTarget.dataset.field;
    let creditType = e.currentTarget.dataset.credit;
    let files = this.data.files;
    this.setData({
      confirmField: field,
      confirmValue: creditType,
      // confirmShow: true
    });
    let that = this;

    if (field == "identificationImg") {
      wx.showModal({
        title: '提示',
        content: '切换车主类型，将清空买家车主证件信息！确认切换？',
        success(res) {
          if (res.confirm) {
            that.handleConfirmOk()
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else if (field == "certificateImg") {
      wx.showModal({
        title: '提示',
        content: '切换是否进口类型将清空已填写数据',
        success(res) {
          if (res.confirm) {
            that.handleConfirmOk()
          }
        }
      })

    }
    // let formData = this.data.formData;
    // let field = e.currentTarget.dataset.field;
    // let creditType = e.currentTarget.dataset.credit;
    // if (field == "buyerCreditFront") {
    //   //买家
    //   formData["buyer.creditType"] = creditType;
    // } else if (field == "sellerCreditFront") {
    //   //卖家
    //   formData["seller.creditType"] = creditType;
    // }
    // this.setData({
    //   formData: formData,
    // });
  },
  //二维码识别扫描
  getQRCode: function(e) {
    var _this = this;
    let formData = this.data.formData;
    wx.scanCode({ //扫描API
      success: function(res) {
        formData[e.currentTarget.dataset.field] = res.result;
        _this.setData({
          formData: formData,
        });
      }
    })
  },
  handleConfirmOk: function() {
    let formData = this.data.formData;
    let field = this.data.confirmField;
    var creditType = this.data.confirmValue;
    console.log(creditType)
    let files = this.data.files;
    if (field == "identificationImg") {
      //买家
      formData["creditType"] = creditType;
      formData["creditNo"] = null;
      formData["name"] = null;
      formData["address"] = null;
      files["identificationImg"] = null;
    } else if (field == "sellerCreditFront") {
      //卖家
      formData["creditType"] = creditType;
      // formData["seller.creditNo"] = null;
      // formData["seller.name"] = null;
      // formData["seller.residenceAddress"] = null;
      files["sellerCreditFront"] = null;
    } else if (field == "certificateImg") {
      console.log()

      //车架号
      formData["vin"] = '';
      //车辆品牌
      formData["brand"] = '';
      //车辆型号
      formData["model"] = '';
      //发动机型号 与 发动机号
      formData["engineModel"] = '';
      formData["engineNo"] = '';
      //出厂日期
      formData["productionDate"] = '';
      formData["isImported"] = creditType;
      files["certificateImg"] = null;


    }
    this.setData({
      formData: formData,
      // confirmShow: false,
      files: files
    });
  },
  //chooseCity
  chooseCity: function(e) {
    let filed = e.currentTarget.dataset.field;
    let formData = this.data.formData;
    // console.log(formData[filed]);

    wx.navigateTo({
      url: '/pages/itemChose/index?filed=' + filed,
    })
  },
  handleConfirmCancel: function() {
    this.setData({
      confirmShow: false
    });
  },
})